{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Tce3stUlHN0L"
   },
   "source": [
    "##### Copyright 2018 The TensorFlow Authors.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "tuOe1ymfHZPu"
   },
   "outputs": [],
   "source": [
    "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "# https://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "MfBg1C5NB3X0"
   },
   "source": [
    "# Use a GPU\n",
    "\n",
    "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://www.tensorflow.org/guide/gpu\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/guide/gpu.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/guide/gpu.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/en/guide/gpu.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
    "  </td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "SoYIwe40vEPI"
   },
   "source": [
    "TensorFlow code, and `tf.keras` models will transparently run on a single GPU with no code changes required.\n",
    "\n",
    "Note: Use `tf.config.experimental.list_physical_devices('GPU')` to confirm that TensorFlow is using the GPU.\n",
    "\n",
    "The simplest way to run on multiple GPUs, on one or many machines, is using [Distribution Strategies](distributed_training.ipynb).\n",
    "\n",
    "This guide is for users who have tried these approaches and found that they need fine-grained control of how TensorFlow uses the GPU."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "MUXex9ctTuDB"
   },
   "source": [
    "## Setup\n",
    "\n",
    "Ensure you have the latest TensorFlow gpu release installed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {
     "height": 34
    },
    "colab_type": "code",
    "id": "IqR2PQG4ZaZ0",
    "outputId": "b80829b0-df1d-4d4e-a6d3-a6531cd211a0"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Num GPUs Available:  2\n"
     ]
    }
   ],
   "source": [
    "from __future__ import absolute_import, division, print_function, unicode_literals\n",
    "\n",
    "try:\n",
    "  # %tensorflow_version only exists in Colab.\n",
    "  %tensorflow_version 2.x\n",
    "except Exception:\n",
    "  pass\n",
    "import tensorflow as tf\n",
    "print(\"Num GPUs Available: \", len(tf.config.experimental.list_physical_devices('GPU')))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ZELutYNetv-v"
   },
   "source": [
    "## Overview\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "xHxb-dlhMIzW"
   },
   "source": [
    "TensorFlow supports running computations on a variety of types of devices, including CPU and GPU. They are represented with string identifiers for example:\n",
    "\n",
    "*   `\"/device:CPU:0\"`: The CPU of your machine.\n",
    "*   `\"/GPU:0\"`: Short-hand notation for the first GPU of your machine that is visible to TensorFlow.\n",
    "*   `\"/job:localhost/replica:0/task:0/device:GPU:1\"`: Fully qualified name of the second GPU of your machine that is visible to TensorFlow.\n",
    "\n",
    "If a TensorFlow operation has both CPU and GPU implementations, by default the GPU devices will be given priority when the operation is assigned to a device. For example, `tf.matmul` has both CPU and GPU kernels. On a system with devices `CPU:0` and `GPU:0`, the `GPU:0` device will be selected to run `tf.matmul` unless you explicitly request running it on another device."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "UhNtHfuxCGVy"
   },
   "source": [
    "## Logging device placement\n",
    "\n",
    "To find out which devices your operations and tensors are assigned to, put\n",
    "`tf.debugging.set_log_device_placement(True)` as the first statement of your\n",
    "program. Enabling device placement logging causes any Tensor allocations or operations to be printed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {
     "height": 85
    },
    "colab_type": "code",
    "id": "2Dbw0tpEirCd",
    "outputId": "f9823d90-64d3-4eef-a6fe-a3bb421e0351"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0\n",
      "tf.Tensor(\n",
      "[[22. 28.]\n",
      " [49. 64.]], shape=(2, 2), dtype=float32)\n"
     ]
    }
   ],
   "source": [
    "tf.debugging.set_log_device_placement(True)\n",
    "\n",
    "# Create some tensors\n",
    "a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\n",
    "b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])\n",
    "c = tf.matmul(a, b)\n",
    "\n",
    "print(c)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "kKhmFeraTdEI"
   },
   "source": [
    "The above code will print an indication the `MatMul` op was executed on `GPU:0`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "U88FspwGjB7W"
   },
   "source": [
    "## Manual device placement\n",
    "\n",
    "If you would like a particular operation to run on a device of your choice\n",
    "instead of what's automatically selected for you, you can use `with tf.device`\n",
    "to create a device context, and all the operations within that context will\n",
    "run on the same designated device."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {
     "height": 85
    },
    "colab_type": "code",
    "id": "8wqaQfEhjHit",
    "outputId": "7bbbb814-13d6-4e00-b4a6-b81d87e1d6ac"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0\n",
      "tf.Tensor(\n",
      "[[22. 28.]\n",
      " [49. 64.]], shape=(2, 2), dtype=float32)\n"
     ]
    }
   ],
   "source": [
    "tf.debugging.set_log_device_placement(True)\n",
    "\n",
    "# Place tensors on the CPU\n",
    "with tf.device('/CPU:0'):\n",
    "  a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\n",
    "  b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])\n",
    "\n",
    "c = tf.matmul(a, b)\n",
    "print(c)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "8ixO89gRjJUu"
   },
   "source": [
    "You will see that now `a` and `b` are assigned to `CPU:0`. Since a device was\n",
    "not explicitly specified for the `MatMul` operation, the TensorFlow runtime will\n",
    "choose one based on the operation and available devices (`GPU:0` in this\n",
    "example) and automatically copy tensors between devices if required."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ARrRhwqijPzN"
   },
   "source": [
    "## Limiting GPU memory growth\n",
    "\n",
    "By default, TensorFlow maps nearly all of the GPU memory of all GPUs (subject to\n",
    "[`CUDA_VISIBLE_DEVICES`](https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#env-vars)) visible to the process. This is done to more efficiently use the relatively precious GPU memory resources on the devices by reducing memory fragmentation. To limit TensorFlow to a specific set of GPUs we use the `tf.config.experimental.set_visible_devices` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {
     "height": 34
    },
    "colab_type": "code",
    "id": "hPI--n_jhZhv",
    "outputId": "0a52d17f-743b-4657-93a8-ee3ece54271a"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2 Physical GPUs, 1 Logical GPU\n"
     ]
    }
   ],
   "source": [
    "gpus = tf.config.experimental.list_physical_devices('GPU')\n",
    "if gpus:\n",
    "  # Restrict TensorFlow to only use the first GPU\n",
    "  try:\n",
    "    tf.config.experimental.set_visible_devices(gpus[0], 'GPU')\n",
    "    logical_gpus = tf.config.experimental.list_logical_devices('GPU')\n",
    "    print(len(gpus), \"Physical GPUs,\", len(logical_gpus), \"Logical GPU\")\n",
    "  except RuntimeError as e:\n",
    "    # Visible devices must be set before GPUs have been initialized\n",
    "    print(e)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "N3x4M55DhYk9"
   },
   "source": [
    "In some cases it is desirable for the process to only allocate a subset of the available memory, or to only grow the memory usage as is needed by the process. TensorFlow provides two methods to control this.\n",
    "\n",
    "The first option is to turn on memory growth by calling `tf.config.experimental.set_memory_growth`, which attempts to allocate only as much GPU memory as needed for the runtime allocations: it starts out allocating very little memory, and as the program gets run and more GPU memory is needed, we extend the GPU memory region allocated to the TensorFlow process. Note we do not release memory, since it can lead to memory fragmentation. To turn on memory growth for a specific GPU, use the following code prior to allocating any tensors or executing any ops."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {
     "height": 34
    },
    "colab_type": "code",
    "id": "jr3Kf1boFnCO",
    "outputId": "a91bc31c-1059-48c2-cf0d-7193c1133db2"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2 Physical GPUs, 2 Logical GPUs\n"
     ]
    }
   ],
   "source": [
    "gpus = tf.config.experimental.list_physical_devices('GPU')\n",
    "if gpus:\n",
    "  try:\n",
    "    # Currently, memory growth needs to be the same across GPUs\n",
    "    for gpu in gpus:\n",
    "      tf.config.experimental.set_memory_growth(gpu, True)\n",
    "    logical_gpus = tf.config.experimental.list_logical_devices('GPU')\n",
    "    print(len(gpus), \"Physical GPUs,\", len(logical_gpus), \"Logical GPUs\")\n",
    "  except RuntimeError as e:\n",
    "    # Memory growth must be set before GPUs have been initialized\n",
    "    print(e)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "I1o8t51QFnmv"
   },
   "source": [
    "Another way to enable this option is to set the environmental variable `TF_FORCE_GPU_ALLOW_GROWTH` to `true`. This configuration is platform specific.\n",
    "\n",
    "The second method is to configure a virtual GPU device with `tf.config.experimental.set_virtual_device_configuration` and set a hard limit on the total memory to allocate on the GPU."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {
     "height": 34
    },
    "colab_type": "code",
    "id": "2qO2cS9QFn42",
    "outputId": "97202153-54fd-41ef-edb4-4738a86d8458"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2 Physical GPUs, 2 Logical GPUs\n"
     ]
    }
   ],
   "source": [
    "gpus = tf.config.experimental.list_physical_devices('GPU')\n",
    "if gpus:\n",
    "  # Restrict TensorFlow to only allocate 1GB of memory on the first GPU\n",
    "  try:\n",
    "    tf.config.experimental.set_virtual_device_configuration(\n",
    "        gpus[0],\n",
    "        [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)])\n",
    "    logical_gpus = tf.config.experimental.list_logical_devices('GPU')\n",
    "    print(len(gpus), \"Physical GPUs,\", len(logical_gpus), \"Logical GPUs\")\n",
    "  except RuntimeError as e:\n",
    "    # Virtual devices must be set before GPUs have been initialized\n",
    "    print(e)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Bsg1iLuHFoLW"
   },
   "source": [
    "This is useful if you want to truly bound the amount of GPU memory available to the TensorFlow process. This is common practice for local development when the GPU is shared with other applications such as a workstation GUI."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "B27_-1gyjf-t"
   },
   "source": [
    "## Using a single GPU on a multi-GPU system\n",
    "\n",
    "If you have more than one GPU in your system, the GPU with the lowest ID will be\n",
    "selected by default. If you would like to run on a different GPU, you will need\n",
    "to specify the preference explicitly:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {
     "height": 34
    },
    "colab_type": "code",
    "id": "wep4iteljjG1",
    "outputId": "79329b7e-b50f-4252-95f2-ffbb0e952532"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/job:localhost/replica:0/task:0/device:GPU:2 unknown device.\n"
     ]
    }
   ],
   "source": [
    "tf.debugging.set_log_device_placement(True)\n",
    "\n",
    "try:\n",
    "  # Specify an invalid GPU device\n",
    "  with tf.device('/device:GPU:2'):\n",
    "    a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\n",
    "    b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])\n",
    "    c = tf.matmul(a, b)\n",
    "except RuntimeError as e:\n",
    "  print(e)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "jy-4cCO_jn4G"
   },
    "source": [
      "If the device you have specified does not exist, you will get a `RuntimeError`: `.../device:GPU:2 unknown device`.\n",
      "\n",
      "If you would like TensorFlow to automatically choose an existing and supported device to run the operations in case the specified one doesn't exist, you can call `tf.config.set_soft_device_placement(True)`."
    ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {
     "height": 85
    },
    "colab_type": "code",
    "id": "sut_UHlkjvWd",
    "outputId": "11433de9-96ba-4a48-d77e-ee433f54123a"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0\n",
      "tf.Tensor(\n",
      "[[22. 28.]\n",
      " [49. 64.]], shape=(2, 2), dtype=float32)\n"
     ]
    }
   ],
   "source": [
    "tf.config.set_soft_device_placement(True)\n",
    "tf.debugging.set_log_device_placement(True)\n",
    "\n",
    "# Creates some tensors\n",
    "a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\n",
    "b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])\n",
    "c = tf.matmul(a, b)\n",
    "\n",
    "print(c)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "sYTYPrQZj2d9"
   },
   "source": [
    "## Using multiple GPUs\n",
    "\n",
    "Developing for multiple GPUs will allow a model to scale with the additional resources. If developing on a system with a single GPU, we can simulate multiple GPUs with virtual devices. This enables easy testing of multi-GPU setups without requiring additional resources."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {
     "height": 34
    },
    "colab_type": "code",
    "id": "8EMGuGKbNkc6",
    "outputId": "36d2a3f4-1aa0-460f-bb2e-acaefa44f1fc"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2 Physical GPU, 3 Logical GPUs\n"
     ]
    }
   ],
   "source": [
    "gpus = tf.config.experimental.list_physical_devices('GPU')\n",
    "if gpus:\n",
    "  # Create 2 virtual GPUs with 1GB memory each\n",
    "  try:\n",
    "    tf.config.experimental.set_virtual_device_configuration(\n",
    "        gpus[0],\n",
    "        [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024),\n",
    "         tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)])\n",
    "    logical_gpus = tf.config.experimental.list_logical_devices('GPU')\n",
    "    print(len(gpus), \"Physical GPU,\", len(logical_gpus), \"Logical GPUs\")\n",
    "  except RuntimeError as e:\n",
    "    # Virtual devices must be set before GPUs have been initialized\n",
    "    print(e)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "xmNzO0FxNkol"
   },
   "source": [
    "Once we have multiple logical GPUs available to the runtime, we can utilize the multiple GPUs with `tf.distribute.Strategy` or with manual placement."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "IDZmEGq4j6kG"
   },
   "source": [
    "#### With `tf.distribute.Strategy`\n",
    "\n",
    "The best practice for using multiple GPUs is to use `tf.distribute.Strategy`.\n",
    "Here is a simple example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {
     "height": 340
    },
    "colab_type": "code",
    "id": "1KgzY8V2AvRv",
    "outputId": "09341ecf-f439-499b-8282-919cbf470c6d"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Executing op RandomUniform in device /job:localhost/replica:0/task:0/device:GPU:0\n",
      "Executing op Sub in device /job:localhost/replica:0/task:0/device:GPU:0\n",
      "Executing op Mul in device /job:localhost/replica:0/task:0/device:GPU:0\n",
      "Executing op Add in device /job:localhost/replica:0/task:0/device:GPU:0\n",
      "Executing op VarHandleOp in device /job:localhost/replica:0/task:0/device:GPU:0\n",
      "Executing op VarIsInitializedOp in device /job:localhost/replica:0/task:0/device:GPU:0\n",
      "Executing op LogicalNot in device /job:localhost/replica:0/task:0/device:GPU:0\n",
      "Executing op Assert in device /job:localhost/replica:0/task:0/device:GPU:0\n",
      "Executing op AssignVariableOp in device /job:localhost/replica:0/task:0/device:GPU:0\n",
      "Executing op ReadVariableOp in device /job:localhost/replica:0/task:0/device:GPU:0\n",
      "Executing op Identity in device /job:localhost/replica:0/task:0/device:GPU:1\n",
      "Executing op VarHandleOp in device /job:localhost/replica:0/task:0/device:GPU:1\n",
      "Executing op VarIsInitializedOp in device /job:localhost/replica:0/task:0/device:GPU:1\n",
      "Executing op LogicalNot in device /job:localhost/replica:0/task:0/device:GPU:1\n",
      "Executing op Assert in device /job:localhost/replica:0/task:0/device:GPU:1\n",
      "Executing op AssignVariableOp in device /job:localhost/replica:0/task:0/device:GPU:1\n",
      "Executing op Reshape in device /job:localhost/replica:0/task:0/device:GPU:0\n",
      "Executing op VarHandleOp in device /job:localhost/replica:0/task:0/device:GPU:0\n",
      "Executing op VarHandleOp in device /job:localhost/replica:0/task:0/device:GPU:1\n"
     ]
    }
   ],
   "source": [
    "tf.debugging.set_log_device_placement(True)\n",
    "\n",
    "strategy = tf.distribute.MirroredStrategy()\n",
    "with strategy.scope():\n",
    "  inputs = tf.keras.layers.Input(shape=(1,))\n",
    "  predictions = tf.keras.layers.Dense(1)(inputs)\n",
    "  model = tf.keras.models.Model(inputs=inputs, outputs=predictions)\n",
    "  model.compile(loss='mse',\n",
    "                optimizer=tf.keras.optimizers.SGD(learning_rate=0.2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Dy7nxlKsAxkK"
   },
   "source": [
    "This program will run a copy of your model on each GPU, splitting the input data\n",
    "between them, also known as \"[data parallelism](https://en.wikipedia.org/wiki/Data_parallelism)\".\n",
    "\n",
    "For more information about distribution strategies, check out the guide [here](./distributed_training.ipynb)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "8phxM5TVkAY_"
   },
   "source": [
    "#### Manual placement\n",
    "\n",
    "`tf.distribute.Strategy` works under the hood by replicating computation across devices. You can manually implement replication by constructing your model on each GPU. For example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {
     "height": 119
    },
    "colab_type": "code",
    "id": "AqPo9ltUA_EY",
    "outputId": "966a7a6e-57ed-4090-92b6-625dc122f60b"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0\n",
      "Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:1\n",
      "Executing op AddN in device /job:localhost/replica:0/task:0/device:CPU:0\n",
      "tf.Tensor(\n",
      "[[ 44.  56.]\n",
      " [ 98. 128.]], shape=(2, 2), dtype=float32)\n"
     ]
    }
   ],
   "source": [
    "tf.debugging.set_log_device_placement(True)\n",
    "\n",
    "gpus = tf.config.experimental.list_logical_devices('GPU')\n",
    "if gpus:\n",
    "  # Replicate your computation on multiple GPUs\n",
    "  c = []\n",
    "  for gpu in gpus:\n",
    "    with tf.device(gpu.name):\n",
    "      a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\n",
    "      b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])\n",
    "      c.append(tf.matmul(a, b))\n",
    "\n",
    "  with tf.device('/CPU:0'):\n",
    "    matmul_sum = tf.add_n(c)\n",
    "\n",
    "  print(matmul_sum)"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "name": "gpu.ipynb",
   "toc_visible": true,
   "version": "0.3.2"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
